package com.mainaer.wjokhttp.ui.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.ArrayList;
import java.util.HashSet;

/**
 * 继承在BaseAdapter，封装必要的功能，子类adapter可以继承此类
 *
 * @param <V> 数据泛型
 * @author wangjian
 */
public abstract class HolderAdapter<V> extends BaseAdapter {
    private HashSet<ViewHolder<V>> holders = new HashSet<ViewHolder<V>>();

    protected Context context;
    
    private ArrayList<V> dataList = new ArrayList<V>();

    public HolderAdapter(Context context) {
        this.context = context;
    }
    
    public ArrayList<V> getDataList() {
        return dataList;
    }
    
    public void setDataList(ArrayList<V> dataList) {
        this.dataList = dataList;
    }
    
    public void clearData(){
        dataList.clear();
    }
    
    @Override
    public V getItem(int position){
        return dataList.get(position);
    }
    
    @Override
    public int getCount() {
        return dataList.size();
    }
    
    @Override
    public long getItemId(int position) {
        return position;
    }
    
    @Override
    public final View getView(int position, View convertView, ViewGroup parent) {

        V obj = getItem(position);

        ViewHolder<V> holder;
        View view;
        if (convertView == null || convertView.getTag() == null) {
            holder = createHolder(obj);
            view = holder.init(obj, parent, context);
            view.setTag(holder);
            holders.add(holder);
        } else {
            holder = (ViewHolder<V>) convertView.getTag();
            view = convertView;
        }

        onBindViewHolder(holder, obj, position, context);

        return view;
    }

    public void onMovedToScrapHeap(View view) {
        if (view.getTag() instanceof ViewHolder) {
            ((ViewHolder) view.getTag()).unbind(false);
        }
    }

    public void dispose() {
        for (ViewHolder holder : holders) {
            holder.unbind(true);
        }
    }

    /**
     * 数据绑定holder
     *
     * @param holder 自定义的holder 类
     * @param obj 数据实体
     * @param position position
     * @param context context
     */
    protected void onBindViewHolder(ViewHolder<V> holder, V obj, int position, Context context) {
        holder.bind(obj, position, context);
    }

    /**
     * 常见view holder
     *
     * @param obj 数据实体类
     * @return
     */
    protected abstract ViewHolder<V> createHolder(V obj);
}
